<template>
  <div class="product-list">
    <div class="content">
      <div class="title">/商品列表</div>
      <div class="search">
        <el-input v-model="search" placeholder="输入商品名称关键字搜索"/>
        <el-button type="primary" @click="submitSearch">查询</el-button>
      </div>
      <el-table
        :data="productList"
        @selection-change="selectAll"
        border
        stripe>

        <el-table-column
          type="selection"
          align="center"
        >
        </el-table-column>


        <el-table-column
          prop="id"
          label="id"
          align="center">
        </el-table-column>

        <el-table-column
          prop="type_name"
          label="类型"
          align="center">
        </el-table-column>

        <el-table-column
          prop="name"
          label="名称"
          align="center"

          :show-overflow-tooltip="true">
        </el-table-column>

        <el-table-column
          prop="disc"
          label="描述"
          align="center"
          :show-overflow-tooltip="true">
        </el-table-column>

        <el-table-column
          prop="principal"
          label="成本价"
          align="center">
        </el-table-column>

        <el-table-column
          prop="price"
          label="销售价"
          align="center">
        </el-table-column>

        <el-table-column label="图片" prop="bannerPic" align="center">
          　　<template slot-scope="scope">
          　　　　<img :src="serverApi+scope.row.pic" width="40" height="40"/>
          　　</template>
        </el-table-column>

        <el-table-column label="详情" prop="detailPic" align="center">
          　　<template slot-scope="scope">
          　　　　<img :src="serverApi+scope.row.detail" width="40" height="40"/>
          　　</template>
        </el-table-column>

        <el-table-column align="center" width="200">
          <template slot="header" slot-scope="scope">
            <el-button
              size="mini"
              @click="handleAdd">新增</el-button>
            <el-button
              size="mini"
              @click="handleBatchDelete">批量下架</el-button>
          </template>
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">下架</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="page">
        <el-pagination
          background
          layout="prev, pager, next"
          :page-count="totalPage"
          @current-change="changePage"
          ref="pagination"
          v-if="productList.length!=0">
        </el-pagination>
      </div>
    </div>
    <el-dialog title="商品列表" :visible.sync="dialogFormVisible" @close="cancelDialog">
      <el-form :model="form" status-icon :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择商品类型">
            <el-option :label="item.name" :value="item.id" :key="index" v-for="(item,index) in typeList"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="disc">
          <el-input type="textarea" v-model="form.disc"></el-input>
        </el-form-item>
        <el-form-item label="成本" prop="principal">
          <el-input v-model="form.principal" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="price">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <div class="pic-item">
          <el-form-item label="图片" prop="bannerPic">
            <el-upload
              class="avatar-uploader"
              :action="serverApi+'images'"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccessPic"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.bannerPic" :src="serverApi+form.bannerPic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="详情" prop="detailPic">
            <el-upload
              class="avatar-uploader"
              :action="serverApi+'images'"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccessDetail"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.detailPic" :src="serverApi+form.detailPic" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="submitProductItem">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import serverApi from "@/api";
  import Vue from "vue";
  import router from "../router";
  export default {
    name: 'ProductList',
    data() {
      const validateFloat = (rule, value, callback) => {
        let reg = /^(-)?(0|[1-9]\d*)(\s|$|\.\d{1,2}\b)/;
        if (!value) {
          callback(new Error('输入的内容不能为空!'))
        }else if(!reg.test(value)){
          callback(new Error('只接受两位数小数的数字！'))
        } else {
          callback()
        }
      };
      return {
        serverApi:serverApi,
        productList:[],
        search:'',
        typeList:[],
        dialogFormVisible: false,
        form: {
          id:null,
          type:'',
          name:'',
          disc:'',
          principal:null,
          price:null,
          bannerPic:'',
          detailPic:''
        },
        rules: {
          type:[{required: true, message: '请选择商品类别', trigger: 'change'}],
          name:[{required: true, message: '请输入商品名字', trigger: 'blur'}],
          disc:[{required: true, message: '请输入商品描述', trigger: 'blur'}],
          principal:[{ required: true, trigger: 'blur',validator: validateFloat }],
          price:[{ required: true, trigger: 'blur',validator: validateFloat }],
          bannerPic:[{required: true, message: '请上传商品banner图片'}],
          detailPic:[{required: true, message: '请上传商品详情图片'}],
        },
        deleteList:[],
        //分页
        totalPage:null,
        currPage:null,
        headers: {"token":JSON.parse(sessionStorage.getItem("userInfo")).token}
      }
    },
    created() {
      //获取类型
      this.getTypeData();
      // 获取商品列表和分页
      this.getProductList();
    },
    watch:{
      search(newVal, oldVal) {
        if (oldVal.lendth > 0 || newVal == '') { //查询
            this.getProductAll();
            this.$refs.pagination.internalCurrentPage = 1;
            this.currPage = 1;
        }
      }
    },
    methods: {
      getTypeData(){
        this.axios.get('/api/product/type',).then((res=>{
          if(res.data.errCode==0){
            this.typeList = res.data.result;
          }
        })).catch(error=>{
          console.log(error)
        });
      },
      //查询数据
      getProductAll(page){
        let url = page?'/api/product/list?page='+page:'/api/product/list';
        this.axios.get(url).then((res=>{
          if(res.data.errCode==0){
            this.totalPage = res.data.data.total_page;
            this.productList = res.data.data.result;
          }else if(res.data.errCode==9){
            this.productList = [];
            this.totalPage = null;
          }
        })).catch(error=>{
          console.log(error)
        });
      },
      //搜索
      submitSearch(page){
        if(!this.search){
          this.$message.error("请输入商品关键字搜索！");
          return
        }
        let currentPage = null;
        if(typeof(page)=="object" || !page){
          currentPage=1;
          this.$refs.pagination.internalCurrentPage = 1;
          this.currPage=1;
        }else{
          currentPage = page;
        }
        let url = '/api/product/search?key='+this.search+'&&page='+currentPage;
        this.axios.get(url).then((res=>{
          console.log(res);
          if(res.data.errCode==9){
            // this.totalPage =null;
            // this.productList = null;
            this.$message.info(res.data.message);
          }else if(res.data.errCode==0){
            this.totalPage = res.data.data.total_page;
            this.productList = res.data.data.result;
          }
        })).catch(error=>{
          console.log(error)
        });
      },
      //判断
      getProductList(currentPage){
        if(this.search){
          this.submitSearch(currentPage)
        }else{
          this.getProductAll(currentPage)
        }
      },
      changePage(currentPage){
        this.currPage = currentPage;
        this.getProductList(currentPage);
      },
      //新增
      handleAdd(){
        this.form={};
        this.dialogFormVisible=true;
      },
      //批量删除
      handleBatchDelete(){
        if(this.deleteList.length<=0){
          this.$message.error('请选择要下架的商品list!');
          return
        }
        let idList = this.deleteList.map((val,index,arr)=>{
          return val.id
        });
        this.$confirm('此操作将批量删除商品信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //批量删除
          this.axios.post('/api/product/removeMore',idList).then((res=>{
            if(res.data.errCode==0){
              this.$message.success(res.data.message);
              this.getProductList();
              this.$refs.pagination.internalCurrentPage = 1;
              this.currPage=1;
            }
          })).catch(error=>{
            console.log(error)
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //单条记录编辑
      handleEdit(row){
        let ProductJson = {
          id:row.id,
          type:row.type_id,
          name:row.name,
          disc:row.disc,
          principal:row.principal,
          price:row.price,
          bannerPic:row.pic,
          detailPic:row.detail
        };
        this.form=ProductJson;
        this.dialogFormVisible=true;
      },
      //单条记录删除
      handleDelete(row){
        this.$confirm('此操作将删除该商品信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //调删除商品接口
          this.axios.post('/api/product/remove',{id:row.id}).then((res=>{
            if(res.data.errCode==0){
              this.$message.success(res.data.message);
              this.getProductList();
              this.$refs.pagination.internalCurrentPage = 1;
              this.currPage=1;
            }
          })).catch(error=>{
            console.log(error)
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      beforeAvatarUpload(file) {
        const isFormat = file.type === 'image/jpeg' || 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isFormat) {
          this.$message.error('上传头像图片只能是JPG或者是PNG格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过2MB!');
        }
        return isFormat && isLt2M;
      },
      handleAvatarSuccessPic(res, file) {
        if(res.errorCode==0){
          this.$message.success(res.message);
          let path = res.newPath;
          let newPath = path.replace(/\\/g,"/");
          this.$set(this.form, 'bannerPic', newPath)
          return
        }else if(res.errorCode==401){
          sessionStorage.removeItem("userInfo" );
          this.$message.error(res.data.message);
          setTimeout(function () {
            router.replace({path:"/login"})
          },1000);
        }
      },
      handleAvatarSuccessDetail(res, file) {
        if(res.errorCode==0){
          this.$message.success(res.message);
          let path = res.newPath;
          let newPath = path.replace(/\\/g,"/");
          this.$set(this.form, 'detailPic', newPath)
        }else if(res.errorCode==401){
          sessionStorage.removeItem("userInfo" );
          this.$message.error(res.data.message);
          setTimeout(function () {
            router.replace({path:"/login"})
          },1000);
        }
      },
      cancelDialog(){
        this.$refs.ruleForm.resetFields();
        this.dialogFormVisible=false;
        this.form = {}
      },
      //弹窗确定
      submitProductItem(){
        this.$refs.ruleForm.validate(valid => {
          let data = this.form;
          data.upper_shelf=1;
          if (valid) {
            //发起请求
            let url = this.form.id==null?'/api/product/add':'/api/product/alter';
            this.axios.post(url,data).then((res=>{
              if(res.data.errCode==0){
                this.$message.success(res.data.message);
                this.getProductList(this.currPage);
                this.dialogFormVisible = false
              }
            })).catch(error=>{
              console.log(error)
            });
          }
        })
      },
      //批量选择
      selectAll(selection){
        this.deleteList = selection;
      }
    }
  }
</script>
<style lang="less" scoped>
  .product-list{
    padding: 0 20px;
    .content{
      .title{
        width: 100%;
        height: 60px;
        line-height: 60px;
      }
      .search{
       margin-bottom: 20px;
        display: flex;
        .el-input{
          width: 300px;
          margin-right: 10px;
        }
      }
    }
    .pic-item{
      display: flex;
    }
    .page{
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border:1px solid #DCDFE6;
    border-radius: 5px;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
